package com.ssyan.appointment.hosp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssyan.appointment.common.exception.AppointmentException;
import com.ssyan.appointment.common.result.Result;
import com.ssyan.appointment.hosp.service.HospitalSetService;
import com.ssyan.appointment.model.hosp.Hospital;
import com.ssyan.appointment.model.hosp.HospitalSet;
import com.ssyan.appointment.utils.MD5;
import com.ssyan.appointment.vo.hosp.HospitalSetQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@Api(tags = "医院设置管理")
@RestController
@RequestMapping("/admin/hosp/hospitalSet")
@CrossOrigin //允许跨域访问
public class HospitalSetController {

    //注入service
    @Autowired
    private HospitalSetService hospitalSetService;

    //1.测试环境：查询医院设置表的所有信息
    //测试url：http://localhost:8201/admin/hosp/hospitalSet/findAll
    @ApiOperation("获取所有医院设置信息")
    @GetMapping("findAll")
    public Result findAllHospitalSet(){
        //调用service方法，IService提供了list()方法，查询所有数据
        List<HospitalSet> list = hospitalSetService.list(null);
        return Result.ok(list);
    }

    //2.逻辑删除医院设置
    @ApiOperation("逻辑删除医院设置信息")
    @DeleteMapping("{id}")
    public Result removeHospSet(@PathVariable
                                 @ApiParam(name = "id",value = "医院ID编号",required = true)
                                            Long id){
        boolean flag = hospitalSetService.removeById(id);
        if (flag){
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    //3.条件查询带分页
    @ApiOperation("获取条件分页查询")
    @PostMapping("findPage/{current}/{limit}")
    /**
     * @RequestBody(required = false):
     * 1.为了便于前端接口开发，VO对象一般添加@RequestBody注解，表示前端传入JSON数据即可自动与对象匹配
     * 2.required = false，表示该数据可以为空
     * 3.JSON传输需要POST请求
     */
    public Result findHospitalSetByCondition(
            @PathVariable
            @ApiParam(name = "current",value = "当前页",required = true)
                    Long current,
            @PathVariable
            @ApiParam(name = "limit",value = "每页记录数",required = true)
                    Long limit,
            @RequestBody(required = false)
                    HospitalSetQueryVo hospitalSetQueryVo){
        //3.1 创建page对象，传递当前页，每页记录数
        Page<HospitalSet> page = new Page<>(current, limit);

        //3.2 构造条件 - 医院名称模糊查询，医院编号精确查询
        QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();

        //Note：逻辑判断，用户是否输入查询条件值，根据不同情况进行判断
        String hosname = hospitalSetQueryVo.getHosname();//医院名称
        String hoscode = hospitalSetQueryVo.getHoscode();//医院编号
        //Note：StringUtils工具类有判断字符串是否为空的方法
        if (StringUtils.hasLength(hosname)){
            wrapper.like("hosname",hospitalSetQueryVo.getHosname());
        }
        if (StringUtils.hasLength(hoscode)){
            wrapper.eq("hoscode",hospitalSetQueryVo.getHoscode());
        }

        //3.3 调用MP提供的page方法实现分页查询
        Page<HospitalSet> pageHospitalSet = hospitalSetService.page(page, wrapper);

        //3.4 返回结果
        return Result.ok(pageHospitalSet);
    }

    //4.添加医院设置
    @ApiOperation("新增医院设置")
    @PostMapping("saveHospitalSet")
    public Result saveHospitalSet(@RequestBody HospitalSet hospitalSet){
        //4.1 设置状态 1-使用 0-不使用
        hospitalSet.setStatus(1);
        //4.2 签名密钥 - 方案：MD5加密（系统时间戳+1000内随机数）
        hospitalSet.setSignKey(
                MD5.encrypt(System.currentTimeMillis()+""+new Random().nextInt(1000)));

        //4.3 调用service层的MP提供的save方法进行设置，返回成功与否
        boolean save = hospitalSetService.save(hospitalSet);

        //4.4 对save结果进行判断来返回result
        if (save){
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    //5.根据id获取医院设置
    @ApiOperation("根据id获取医院设置")
    @GetMapping("getHospitalSet/{id}")
    public Result getHospitalSet(@PathVariable Long id){
        HospitalSet hospitalSet = hospitalSetService.getById(id);

        try {
            //人为制造500错误
            //调用自定义异常
            /*int a = 1/0;*/
        } catch (Exception e){
            throw new AppointmentException("预约失败",201);
        }


        return Result.ok(hospitalSet);
    }

    //6.修改医院设置
    @ApiOperation("修改医院设置")
    @PostMapping("updateHospitalSet")
    public Result updateHospitalSet(@RequestBody HospitalSet hospitalSet){
        boolean flag = hospitalSetService.updateById(hospitalSet);
        if (flag){
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    //7.批量删除医院设置
    @ApiOperation("批量删除医院设置")
    @DeleteMapping("batchRemove")
    public Result batchRemoveHospitalSet(@RequestBody List<Long> idlist){
        boolean flag = hospitalSetService.removeByIds(idlist);
        if (flag){
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    //8.医院设置锁定和解锁 -- 根据id和status设置
    @ApiOperation("医院设置锁定和解锁")
    @PutMapping("lockHospitalSet/{id}/{status}")
    public Result lockHospitalSet(@PathVariable Long id,
                                  @PathVariable Integer status){
        //根据id查询医院设置信息
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        //设置锁定与解锁状态
        hospitalSet.setStatus(status);
        //调用方法更新信息
        hospitalSetService.updateById(hospitalSet);
        return Result.ok();

    }

    //9.发送签名密钥 -- 结合短信服务
    @ApiOperation("发送签名密钥")
    @PutMapping("sendKey/{id}/{status}")
    public Result sendKey(@PathVariable Long id){
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        String signKey = hospitalSet.getSignKey();
        String hoscode = hospitalSet.getHoscode();
        //TODO:发送短信
        return Result.ok();
    }
}
